<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Spring框架2">
<meta property="og:type" content="article">
<meta property="og:title" content="Java日拱一卒-day23">
<meta property="og:url" content="http://yoursite.com/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/index.html">
<meta property="og:site_name" content="很惭愧，就做了一点微小的工作">
<meta property="og:description" content="Spring框架2">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://yoursite.com/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/pic1.jpg">
<meta property="og:image" content="http://yoursite.com/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/pic2.jpg">
<meta property="article:published_time" content="2020-06-12T06:19:52.000Z">
<meta property="article:modified_time" content="2020-07-07T08:49:50.412Z">
<meta property="article:author" content="文予">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://yoursite.com/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/pic1.jpg">

<link rel="canonical" href="http://yoursite.com/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Java日拱一卒-day23 | 很惭愧，就做了一点微小的工作</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">很惭愧，就做了一点微小的工作</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">念念不忘，必有回响</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/uploads/wenyu.png">
      <meta itemprop="name" content="文予">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="很惭愧，就做了一点微小的工作">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java日拱一卒-day23
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-06-12 14:19:52" itemprop="dateCreated datePublished" datetime="2020-06-12T14:19:52+08:00">2020-06-12</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-07 16:49:50" itemprop="dateModified" datetime="2020-07-07T16:49:50+08:00">2020-07-07</time>
              </span>

          
            <div class="post-description">Spring框架2</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="控制反转"><a href="#控制反转" class="headerlink" title="控制反转"></a>控制反转</h2><p>IoC是<code>Inversion of Control</code>的缩写，一般翻译为<code>控制反转</code>，个人觉得翻译为<code>控制倒置</code>更确切(与“举证倒置”等概念一致)。简单来说就是吧复杂的系统分解为相互合作的对象，这些对象类通过封装之后，内部实现对外是透明的，从而降低了解决问题的复杂的度，而且可以灵活的重用与扩展。实现思路简单来说是这样的：借助于第三方实现具有依赖关系的对象之间的解耦。</p>
<p><img src="/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/pic1.jpg" alt="耦合的对象"></p>
<p>解耦之前，类似于齿轮组中齿轮的啮合关系，对象之间的耦合关系是不可避免且必要的。但是醉着应用规模越来越庞大，对象依赖关系也越来越复杂。对于对象之间耦合度过高的系统，必然会出现牵一发而动全身的情形。</p>
<p><img src="/2020/06/12/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day23/pic2.jpg" alt="IoC解耦"></p>
<p>由于引入了中间位置的第三方：IoC容器，使得A、B、C、D四个对象没有了耦合关系，齿轮的传动全部依赖第三方，全部对象的控制权上缴给第三方IoC容器。此时各个对象之间已经没有依赖关系了，实现一个类的的时候无需考虑其他的类。</p>
<h2 id="依赖注入"><a href="#依赖注入" class="headerlink" title="依赖注入"></a>依赖注入</h2><p>所谓依赖注入，就是由IoC容器在运行期间，动态地将某种依赖关系注入到对象之中。控制反转是世界观，依赖注入就是方法论。简单来说就是</p>
<blockquote>
<p>本来需要接受各州参数来构造一个对象，现在只需要接受一个参数：已经实例化的对象</p>
</blockquote>
<p>也就是说，对于对象的依赖是注入进来的，而和他的构造方式解耦了。构造它这个控制操作也交给了第三方，这就是控制反转</p>
<h2 id="注入方法"><a href="#注入方法" class="headerlink" title="注入方法"></a>注入方法</h2><p>假设说有这样一个<code>船(ship)</code>类，那么显然成员变量中需要一个<code>桨(paddle)</code>类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Ship</span></span>&#123;</span><br><span class="line">    Paddle p = <span class="keyword">new</span> Paddle();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果船要做什么事，肯定是需要桨的参与，所以十分依赖桨。现在有这样一个需求：桨需要统一长度为10米。这时候我们需要在构造方法中这么写：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Ship</span></span>&#123;</span><br><span class="line">    Paddle p = <span class="keyword">new</span> Paddle(<span class="number">10</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时这一个改动同时需要修改桨的类(加入长度属性)，又需要修改Ship类其中的<code>new Paddle()</code>以传入长度。此时代码的耦合度高，需要解耦。</p>
<h3 id="构造方法注入"><a href="#构造方法注入" class="headerlink" title="构造方法注入"></a>构造方法注入</h3><p>重构代码的时候不用管依赖的桨的长短，颜色等属性，因为船构造方法依赖了桨，任由桨如何设计，使用的时候传入一个桨即可(用 时候传入而不是针对下层修改)</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Ship</span></span>&#123;</span><br><span class="line">    Paddle p;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Ship</span><span class="params">(Paddle p)</span></span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.p = p;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="工厂模式注入"><a href="#工厂模式注入" class="headerlink" title="工厂模式注入"></a>工厂模式注入</h3><p>新需求如下：桨的生产商认为不能在各地的船使用之前都制造一个桨，因为这造成了多出代码依赖桨，这样如果以后需要修改桨的规范就需要到处去改，太麻烦且容易错误不统一。</p>
<p>一个很容易想到的方法就是搞一个全国工厂(Factory类)，全国需要的桨都在此处进行生产，船就只需要关注Factory()类的方法即可(核心业务逻辑需要依赖的类，该类的实例化交给第三方类进行注入)</p>
<p>实现如下：</p>
<p>工厂模式，新增Factory工厂类去注入</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Factory</span></span>&#123;</span><br><span class="line">    <span class="comment">//通过msg确定需要什么长度颜色大小的桨，此后 的约束拓展在这个类中就可以进行</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Paddle <span class="title">getPaddle</span><span class="params">(String msg)</span></span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(msg==<span class="number">10</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Paddle(<span class="number">10</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span> <span class="keyword">if</span>(msg==<span class="string">"red"</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">new</span> Paddle(<span class="string">"red"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时船的类则变为</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Ship</span></span>&#123;</span><br><span class="line">    Paddle p;</span><br><span class="line">    Factory f = <span class="keyword">new</span> Factory();</span><br><span class="line">    p = f.getPaddle(<span class="string">"red"</span>); <span class="comment">//得到了红色的桨</span></span><br><span class="line">    p = f.getPaddle(<span class="number">10</span>); <span class="comment">//得到了长度为10的桨</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="框架注入"><a href="#框架注入" class="headerlink" title="框架注入"></a>框架注入</h3><p>框架注入本质上还是工厂设计模式的具体实现，本质上还是第三方依赖注入，但是这个第三方可以脱离类，将对象依赖映射信息存储在容器中(xml或者特定的对象中)并且实现动态注入。需要用的时候直接拿。</p>

    </div>

    
    
    

      <footer class="post-footer">

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/05/30/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day22/" rel="prev" title="Java日拱一卒-day22">
      <i class="fa fa-chevron-left"></i> Java日拱一卒-day22
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/07/01/Java%E6%97%A5%E6%8B%B1%E4%B8%80%E5%8D%92-day24/" rel="next" title="Java日拱一卒-day24">
      Java日拱一卒-day24 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#控制反转"><span class="nav-number">1.</span> <span class="nav-text">控制反转</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#依赖注入"><span class="nav-number">2.</span> <span class="nav-text">依赖注入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#注入方法"><span class="nav-number">3.</span> <span class="nav-text">注入方法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#构造方法注入"><span class="nav-number">3.1.</span> <span class="nav-text">构造方法注入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#工厂模式注入"><span class="nav-number">3.2.</span> <span class="nav-text">工厂模式注入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#框架注入"><span class="nav-number">3.3.</span> <span class="nav-text">框架注入</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="文予"
      src="/uploads/wenyu.png">
  <p class="site-author-name" itemprop="name">文予</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">29</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文予</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>


        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>











<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'forest',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  

</body>
</html>
